package cn.jeeweb.modules.client.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import cn.jeeweb.core.common.controller.BaseBeanController;
import cn.jeeweb.core.model.AjaxJson;
import cn.jeeweb.core.model.PageJson;
import cn.jeeweb.core.query.data.PropertyPreFilterable;
import cn.jeeweb.core.query.data.Queryable;
import cn.jeeweb.core.query.utils.QueryableConvertUtils;
import cn.jeeweb.core.query.wrapper.EntityWrapper;
import cn.jeeweb.core.security.shiro.authz.annotation.RequiresMethodPermissions;
import cn.jeeweb.core.security.shiro.authz.annotation.RequiresPathPermission;
import cn.jeeweb.core.utils.MyBeanUtils;
import cn.jeeweb.core.utils.ObjectUtils;
import cn.jeeweb.core.utils.StringUtils;
import cn.jeeweb.core.utils.ZipUtils;
import cn.jeeweb.modules.client.entity.ClientOrder;
import cn.jeeweb.modules.client.entity.Task;
import cn.jeeweb.modules.client.service.ITaskService;
import cn.jeeweb.modules.client.style.ExcelExportStatisticStyler;
import cn.jeeweb.modules.client.style.MapImportHandler;
import cn.jeeweb.modules.sys.utils.UserUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializeFilter;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.*;
import java.util.zip.ZipOutputStream;

/**
 * @Title: 订单拆分
 * @Description: 订单拆分
 * @author zhuht
 * @date 2018-04-13 22:05:39
 * @version V1.0
 *
 */
@Controller
@RequestMapping("${admin.url.prefix}/client/split")
@RequiresPathPermission("client:split")
public class SplitController extends BaseBeanController<Task> {
    @Autowired
    private ITaskService taskService;

    public Task get(String id) {
        if (!ObjectUtils.isNullOrEmpty(id)) {
            return taskService.selectById(id);
        } else {
            return newModel();
        }
    }

    @RequiresMethodPermissions("list")
    @RequestMapping(method = RequestMethod.GET)
    public String list(Model model, HttpServletRequest request, HttpServletResponse response) {
        return display("list");
    }

    @RequestMapping(value = "ajaxList", method = { RequestMethod.GET, RequestMethod.POST })
    private void ajaxList(Queryable queryable, PropertyPreFilterable propertyPreFilterable, HttpServletRequest request,
                          HttpServletResponse response) throws IOException {
        EntityWrapper<Task> entityWrapper = new EntityWrapper<Task>(entityClass);
        propertyPreFilterable.addQueryProperty("id");
        // 预处理
        //entityWrapper.eq("status", 0);
        entityWrapper.eq("createBy.id", UserUtils.getUser().getId());
        QueryableConvertUtils.convertQueryValueToEntityValue(queryable, entityClass);
        SerializeFilter filter = propertyPreFilterable.constructFilter(entityClass);
        PageJson<Task> pagejson = new PageJson<Task>(taskService.list(queryable,entityWrapper));
        String content = JSON.toJSONString(pagejson, filter);
        StringUtils.printJson(response, content);
    }


    @RequestMapping(value = "split", method = { RequestMethod.GET, RequestMethod.POST })
    @ResponseBody
    public AjaxJson split() {
        AjaxJson ajaxJson = new AjaxJson();
        ajaxJson.success("保存成功");

        try {
            List<ClientOrder> orders = new ArrayList<ClientOrder>();
            List<Task> tasks = taskService.selectList(new com.baomidou.mybatisplus.mapper.EntityWrapper<Task>().eq("status","1"));
            List<Task> ts = new ArrayList<Task>();
            for(Task bean:tasks){
                for(int i=0;i<bean.getOrderCount();i++){
                    ClientOrder order = new ClientOrder();
                    MyBeanUtils.copyBean2Bean(order,bean);
                    order.setPrice(String.valueOf(bean.getPrice()));
                    order.setId(null);
                    order.setTaskId(bean.getId());
                    orders.add(order);
                }
                Task task = new Task();
                task.setId(bean.getId());
                task.setStatus(2);
                ts.add(task);
            }

            taskService.splitTask(ts,orders);
        } catch (Exception e) {
            e.printStackTrace();
            ajaxJson.fail("保存失败!<br />原因:" + e.getMessage());
        }
        return ajaxJson;
    }


    @RequestMapping(value = "import", method = { RequestMethod.GET, RequestMethod.POST })
    public String importExc(Model model, HttpServletRequest request, HttpServletResponse response) {
        return display("import");
    }

    //导入EXCEL
    @RequestMapping(value = "export", method = { RequestMethod.GET, RequestMethod.POST })
    public void export(HttpServletRequest request,HttpServletResponse response, @RequestParam("file") MultipartFile file)throws Exception{

        if (file.isEmpty()) {
            return;
        }
        //获取根路径
        ServletContext sc = request.getSession().getServletContext();
        String path = sc.getRealPath("/") + "temp/";
        ZipOutputStream out = new ZipOutputStream(response.getOutputStream());
        String zipName = "日清.zip";
        response.setContentType("APPLICATION/OCTET-STREAM");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(zipName, "UTF-8"));
        Map<String,List> group = new HashMap<String,List>();
        try {
            ImportParams iparams = new ImportParams();
            iparams.setTitleRows(0);
            iparams.setHeadRows(1);
            iparams.setDataHandler(new MapImportHandler());
            List<Map<String, Object>> list = ExcelImportUtil.importExcel(file.getInputStream(), Map.class, iparams);

            for(Map row :list) {
                List rows = group.get(row.get("shopName")) == null ? new ArrayList() : group.get(row.get("shopName"));
                rows.add(row);
                group.put(row.get("shopName").toString(), rows);
            }

            //单个任务
            List<ExcelExportEntity> orde = new ArrayList<ExcelExportEntity>();
            ExcelExportEntity shops_name = new ExcelExportEntity("店铺名称", "shopName");
            shops_name.setWidth(50);
            orde.add(shops_name);
            ExcelExportEntity ww_name = new ExcelExportEntity("旺旺号", "wwName");
            ww_name.setWidth(50);
            orde.add(ww_name);
            orde.add(new ExcelExportEntity("付款金额", "price"));
            for(String key : group.keySet()) {
                ExportParams params = new ExportParams("", "", ExcelType.XSSF);
                params.setStyle(ExcelExportStatisticStyler.class);
                List gr = group.get(key);
                Workbook workbook = ExcelExportUtil.exportExcel(params, orde, gr);
                String hzPath = path+key+ ".xlsx";
                File f = new File(hzPath);
                FileOutputStream fos = new FileOutputStream(f);
                workbook.write(fos);
                fos.close();
                ZipUtils.doCompress(hzPath, out);
                f.delete();
            }
            response.flushBuffer();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            out.close();
        }
    }

    @RequestMapping(value = "delete", method = { RequestMethod.GET, RequestMethod.POST })
    @ResponseBody
    public AjaxJson delete() {
        AjaxJson ajaxJson = new AjaxJson();
        ajaxJson.success("删除成功");
        try {
            taskService.delete(null);
        } catch (Exception e) {
            e.printStackTrace();
            ajaxJson.fail("删除失败");
        }
        return ajaxJson;
    }
}
